package com.test.lock;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Consumer implements Runnable {
    private ConcurrentLinkedQueue<Integer> container;
    private ReentrantLock lock;
    private Condition producerCondition;
    private Condition consumerCondition;

    public Consumer(ConcurrentLinkedQueue<Integer> container, ReentrantLock lock, Condition producerCondition, Condition consumerCondition) {
        this.container = container;
        this.lock = lock;
        this.producerCondition = producerCondition;
        this.consumerCondition = consumerCondition;
    }

    public void consume() {
        System.out.println(container);
        try {
            //获得锁
            lock.lock();
            //容器空了，需要生产
            if (container.isEmpty()) {
                System.out.println("消费完了。。。。");
                consumerCondition.await();
            }
            Integer p = container.poll();
            if (p == null) {
                return;
            }
            //模拟1秒消费一个产品
            TimeUnit.MILLISECONDS.sleep(1000);
            System.out.println("消费产品：" + p);
            //消费一个产品，通知生产者
            producerCondition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //释放锁
            lock.unlock();
        }
    }

    @Override
    public void run() {
        while (true) {
            consume();
        }
    }
}
